package controller

import (
	"net/http"
	"strconv"

	"github.com/example/video_backend/internal/service"
	"github.com/example/video_backend/pkg/logger"
	"github.com/gin-gonic/gin"
)

// PlayHistoryController 播放历史控制器
type PlayHistoryController struct {
	playHistoryService service.PlayHistoryService
}

// NewPlayHistoryController 创建播放历史控制器实例
func NewPlayHistoryController(playHistoryService service.PlayHistoryService) *PlayHistoryController {
	return &PlayHistoryController{playHistoryService: playHistoryService}
}

// AddPlayHistory 添加播放历史
type AddPlayHistoryRequest struct {
	VideoID  uint    `json:"video_id" binding:"required,gt=0"`
	Progress float64 `json:"progress" binding:"gte=0"` // 播放进度，单位为秒
}

// @Summary 添加播放历史
// @Description 添加或更新视频播放历史记录
// @Tags 播放历史
// @Accept json
// @Produce json
// @Security Bearer
// @Param request body AddPlayHistoryRequest true "添加播放历史请求参数"
// @Success 200 {object} Response
// @Router /api/v1/play-history [post]
func (c *PlayHistoryController) AddPlayHistory(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	uid, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	var req AddPlayHistoryRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		logger.Error("Add play history request binding error: " + err.Error())
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	if err := c.playHistoryService.AddOrUpdatePlayHistory(ctx, uid, req.VideoID, req.Progress); err != nil {
		logger.Error("Add play history error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "添加成功"})
}

// GetPlayHistoryList 获取播放历史列表
type GetPlayHistoryListRequest struct {
	Page     int `form:"page,default=1" binding:"gt=0"`
	PageSize int `form:"page_size,default=20" binding:"gt=0,lt=100"`
}

// @Summary 获取播放历史列表
// @Description 获取当前登录用户的播放历史记录
// @Tags 播放历史
// @Accept json
// @Produce json
// @Security Bearer
// @Param page query int false "页码，默认1"
// @Param page_size query int false "每页数量，默认20，最大100"
// @Success 200 {object} Response{data=map[string]interface{}}
// @Router /api/v1/play-history [get]
func (c *PlayHistoryController) GetPlayHistoryList(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	uid, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	var req GetPlayHistoryListRequest
	if err := ctx.ShouldBindQuery(&req); err != nil {
		logger.Error("Get play history list request binding error: " + err.Error())
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	historyList, total, err := c.playHistoryService.GetUserPlayHistory(ctx, uid, req.Page, req.PageSize)
	if err != nil {
		logger.Error("Get play history list error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	response := map[string]interface{}{
		"list":      historyList,
		"total":     total,
		"page":      req.Page,
		"page_size": req.PageSize,
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "获取成功", Data: response})
}

// DeletePlayHistory 删除单条播放历史
// @Summary 删除单条播放历史
// @Description 删除指定的播放历史记录
// @Tags 播放历史
// @Accept json
// @Produce json
// @Security Bearer
// @Param id path int true "历史记录ID"
// @Success 200 {object} Response
// @Router /api/v1/play-history/{id} [delete]
func (c *PlayHistoryController) DeletePlayHistory(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	_, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	// 获取历史记录ID
	historyID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的历史记录ID"})
		return
	}

	if err := c.playHistoryService.DeletePlayHistory(ctx, uint(historyID)); err != nil {
		logger.Error("Delete play history error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "删除成功"})
}

// ClearPlayHistory 清空播放历史
// @Summary 清空播放历史
// @Description 清空当前登录用户的所有播放历史记录
// @Tags 播放历史
// @Accept json
// @Produce json
// @Security Bearer
// @Success 200 {object} Response
// @Router /api/v1/play-history/clear [post]
func (c *PlayHistoryController) ClearPlayHistory(ctx *gin.Context) {
	// 从上下文中获取用户ID
	userID, exists := ctx.Get("userID")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "未登录"})
		return
	}

	uid, ok := userID.(uint)
	if !ok {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "无效的用户ID"})
		return
	}

	if err := c.playHistoryService.ClearUserPlayHistory(ctx, uid); err != nil {
		logger.Error("Clear play history error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "清空成功"})
}
